# 编译器和工具
DCC = dcc
FLANG = flang

# 基本编译标志
DCC_BASE_FLAGS = -fPIE
FLANG_BASE_FLAGS = -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa

# 检查是否设置了ROCM_PATH
ifndef ROCM_PATH
    $(error ROCM_PATH is not set. Please set the ROCM_PATH environment variable)
endif

# 尝试使用rocminfo动态检测GPU架构
GFX_ARCH := $(shell rocminfo 2>/dev/null | grep -oP 'gfx\w+' | uniq)
ifndef GFX_ARCH
    $(warning ROCm architecture not found via rocminfo, using default gfx906)
    GFX_ARCH = gfx906
else
   $(info Detected GPU architecture: $(GFX_ARCH))
endif

# 添加特定架构的标志
DCC_ARCH_FLAGS = --offload-arch=$(GFX_ARCH)
FLANG_ARCH_FLAGS = -march=$(GFX_ARCH)

# 链接器标志和库
# LDFLAGS = -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=$(GFX_ARCH)
LDFLAGS = -B /usr/lib/gcc/x86_64-kylin-linux/12/ -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=$(GFX_ARCH)
LIBS = -L$${ROCM_PATH}/lib -lamdhip64


# 获取当前Makefile所在目录的绝对路径
MAKEFILE_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))

# 源文件
CXX_SRC = $(MAKEFILE_DIR)/test_hip_kernel.cpp
F90_SRCS = $(MAKEFILE_DIR)/hip_wrapper.f90 \
            $(MAKEFILE_DIR)/test_with_hip_omp.f90

# 目标文件（来自C++和Fortran源文件）
OBJS = test_hip_kernel.o hip_wrapper.o test_with_hip_omp.o

# 目标可执行文件
TARGET = test_hip_omp_mixed_program

# 默认目标：构建可执行文件
all: $(TARGET)

# 编译C++源文件的规则
test_hip_kernel.o: $(CXX_SRC)
	$(DCC) -c $(DCC_BASE_FLAGS) $(DCC_ARCH_FLAGS) $< -o $@

# 编译hip_wrapper Fortran源文件的规则
hip_wrapper.o: $(MAKEFILE_DIR)/hip_wrapper.f90
	$(FLANG) -c $(FLANG_BASE_FLAGS) $(FLANG_ARCH_FLAGS) $< -o $@

# 编译test_with_hip_omp Fortran源文件的规则
test_with_hip_omp.o: $(MAKEFILE_DIR)/test_with_hip_omp.f90
	$(FLANG) -c $(FLANG_BASE_FLAGS) $(FLANG_ARCH_FLAGS) $< -o $@

# 将所有目标文件链接为最终可执行文件的规则
$(TARGET): $(OBJS)
	$(FLANG) $(LDFLAGS) $(OBJS) $(LIBS) -o $@

# 清理构建产物
clean:
	rm -f $(OBJS) $(TARGET) *.mod

# 伪目标（不代表实际文件）
.PHONY: all clean